package dk.nordahl.btremote;


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Set;


import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.Switch;

public class BTRemoteMainActivity extends Activity {
	
	private BluetoothAdapter myBlueAdapter = BluetoothAdapter.getDefaultAdapter();


    private ArrayAdapter<String> newDevicelistAA;
    private ArrayAdapter<String> pairedAdapter;
    private final ArrayList<String> pairedList = new ArrayList<String>();
    private final ArrayList<String> nonPairedList = new ArrayList<String>();
    private ArrayList<BluetoothDevice> btDevices = new ArrayList<BluetoothDevice>();
    private BluetoothDevice myDevice;
    private final int REQUEST_ENABLE_BT = 0;
    private Button btnScan;
    private Switch btSwitch;
    
    private BTRemote btr;
  
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {

    	
    	btr = (BTRemote)getApplication(); 
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_btremote_main);
        

        //List of devices in range
        ListView newDeviceView = (ListView)findViewById(R.id.nonPairedListView);
        newDevicelistAA = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, nonPairedList);
        
        newDeviceView.setAdapter(newDevicelistAA);
        newDeviceView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long arg3) {
				myDevice = btDevices.get(position);
		        
				if(!myBlueAdapter.getBondedDevices().contains(myDevice)) 
				{
					pairDevices(myDevice);
				}
				else
				{
					startRemote();
				}

			}
        	
		});

        ListView pairedView = (ListView)findViewById(R.id.pariedListView);
        pairedAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, pairedList);
        pairedView.setAdapter(pairedAdapter);
        
        
        btnScan = (Button)findViewById(R.id.scanBtn);
        btSwitch = (Switch)findViewById(R.id.btSwitch);

        
        //Check to see if this unit supports bluetooth
        if(myBlueAdapter==null)
        {
        	btSwitch.setEnabled(false);
        }
        else
        {
        	btSwitch.setEnabled(true);
        	if(myBlueAdapter.isEnabled())
        	{
        		btSwitch.setChecked(true);
        	}
        	else
        	{
        		btSwitch.setChecked(false);
        	}
        }
        btSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(btSwitch.isChecked())
				{
					Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
					startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
				}
				else
				{
					
					myBlueAdapter.disable();
					newDevicelistAA.clear();
				}	
			}
		});
        btnScan.setOnClickListener(new OnClickListener() {
	
			@Override
			public void onClick(View v) {
				
				newDevicelistAA.clear();
				btDevices.clear();
				myBlueAdapter.startDiscovery(); 
				fillPariedDevices();
				
			}
		});

        registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
        fillPariedDevices();
    } 
    private void startRemote()
    {
    	myBlueAdapter.cancelDiscovery();
    	btr.setBtDevice(myDevice);
    	Intent commandCenter = new Intent(BTRemoteMainActivity.this, Command.class);
    	startActivity(commandCenter);

		 
	
		
	
    	
    }
    @Override
    protected void onPause() {

    	super.onPause();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if (requestCode == REQUEST_ENABLE_BT) {
    	switch (resultCode)
    	{
    	    case RESULT_OK:
    	        myBlueAdapter.startDiscovery();
				fillPariedDevices();
    	    break;
    	}

    		
    	}
    }
    

    private void fillPariedDevices()
    {
    		pairedAdapter.clear();
        	Set<BluetoothDevice> pairedDevices = myBlueAdapter.getBondedDevices();
        	if(pairedDevices.size() > 0)
        	{
        		for(BluetoothDevice btd: pairedDevices)
        		{
        			pairedAdapter.add(btd.getName() + "\n" + btd.getAddress());
        		}

        	}
    }
    private boolean pairDevices(BluetoothDevice device)
    {
    	boolean succes = false;
		Log.i("Log", "Now parring with : "+ device.toString());
		Method m = null;
		try 
		{
			m = device.getClass().getMethod("createBond", (Class[]) null);
	        try 
	        {
			    m.invoke(device, (Object[]) null);
	        	Log.i("Log", "The device : "+ device.toString() + " has been paired with this unit");
				succes = true;
			} 
	        catch (IllegalAccessException e)
	        {
				Log.e("Log", e.getMessage());
				succes = false;
			} 
	        catch (IllegalArgumentException e)
	        {
				Log.e("Log", e.getMessage());
				succes = false;
			} 
	        catch (InvocationTargetException e)
	        {
				Log.e("Log", e.getMessage());
				succes = false;
			}
		}
		catch (NoSuchMethodException e)
		{
			Log.e("Log", e.getMessage());
		}


		return succes;
    	
    }
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    	public void onReceive(Context context, Intent intent) {
    	    String action = intent.getAction();
    	    if (BluetoothDevice.ACTION_FOUND.equals(action)) 
    	    {
    	        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    	        newDevicelistAA.add(device.getName() + "\n" + device.getAddress());
    	        btDevices.add(device);
    	        newDevicelistAA.notifyDataSetChanged();
    	    }
    	  }
    	};

    
}
